use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        println!("Connection established!");
        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let request_line: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();

    println!("Request: {:#?}", request_line);
    println!("head:{}", request_line[0]);

    let response: std::string::String;
    if request_line[0] == "GET /hello HTTP/1.1" {
        response = handle_hello();
    } else {
        let status_line = "HTTP/1.1 200 OK";


        let mut contents = String::from("");
        for (_, v) in request_line.iter().enumerate() {
            contents.push_str(v);
        }

        let length = contents.len();
        response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n\n{contents}");
    }

    stream.write_all(response.as_bytes()).unwrap();
}

fn handle_hello() -> String {
    let status_line = "HTTP/1.1 200 OK";
    let contents = fs::read_to_string("hello.html").unwrap();
    let length = contents.len();
    let ret = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n\n{contents}");
    ret
}

